﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sands.Common;
using Sands.Web;

namespace jUploader_Demo
{
    public partial class upload : System.Web.UI.Page
    {
        private enum FileType
        {
            Image = 0,
            File,
            Media
        }

        public string fileDir { get { return "dir".GetStrParam(); } }//上传文件夹地址
        public int Size { get { return "size".GetIntParam(); } }//上传文件大小
        public int fileType { get { return "type".GetIntParam(); } }//文件类型 0:图片,1文件



        protected void Page_Load(object sender, EventArgs e)
        {
            // 这里只是简单的直接保存到 UploadFiles 目录
            if (Request.Files.Count > 0)
            {
                string ext = System.IO.Path.GetExtension(Request.Files[0].FileName).ToLower();//文件后缀名
                if (checkFileType(Request.Files[0].FileName, fileType) && Request.Files[0].ContentLength <= 512 * 1024 * 1024)
                {
                    string fileName = Guid.NewGuid().ToString("N") + ext;
                    Request.Files[0].SaveAs(Server.MapPath(fileDir) + fileName);
                    Response.Write("{ success: true, fileUrl:'" + fileDir + fileName + "' }");
                    Response.End();
                }
            }
            else
            {
                Response.Write("{ success: false, fileUrl:'' }");
                Response.End();
            }
        }

        //判断上传文件类型
        private bool checkFileType(string file, int type)
        {
            switch ((FileType)type)
            {
                case FileType.Image: return FileHelper.IsEqualsType(file, FileHelper.filetype_image);
                case FileType.File: return FileHelper.IsEqualsType(file, FileHelper.filetype_file);
                case FileType.Media: return FileHelper.IsEqualsType(file, FileHelper.filetype_media);
                default: return false;
            }
        }
    }
}